package com.boruan.shengtangfeng.api.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import com.boruan.shengtangfeng.core.dao.IModuleVideoDao;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.vo.*;
import com.boruan.shengtangfeng.core.vo.mapper.*;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boruan.shengtangfeng.api.jwt.UserSubject;
import com.boruan.shengtangfeng.api.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.service.IAdvertiseService;
import com.boruan.shengtangfeng.core.service.IArticleService;
import com.boruan.shengtangfeng.core.service.IConfigService;
import com.boruan.shengtangfeng.core.service.IGradeService;
import com.boruan.shengtangfeng.core.service.IModuleRecordService;
import com.boruan.shengtangfeng.core.service.IModuleService;
import com.boruan.shengtangfeng.core.service.IQuestionService;
import com.boruan.shengtangfeng.core.service.ISubjectService;
import com.boruan.shengtangfeng.core.service.IUserService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: 刘光强
 * @Description: 首页接口
 * @date:2020年3月10日 上午11:14:10
 */
@Slf4j
@RestController
@SuppressWarnings("all")
@RequestMapping("/api/home")
@Api(value = "", tags = {"NO:5 淘学主页相关接口"})
public class HomeApi {
    @Autowired
    private IAdvertiseService advertiseService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGradeService gradeService;
    @Autowired
    private ISubjectService subjectService;
    @Autowired
    private IModuleService moduleService;
    @Autowired
    private IModuleRecordService moduleRecordService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
	private IModuleVideoDao iModuleVideoDao;


    @GetMapping("/getHomeAdvertise")
    @ApiOperation(value = "NO:5-1 获取首页轮播图 不需要登录", notes = "")
    public GlobalReponse<List<AdvertiseVo>> getHomeAdvertise() {
        List<Advertise> result = advertiseService.getList(1, 0);
        return GlobalReponse.success(AdvertiseVoMapper.MAPPER.toVo(result));
    }

    @GetMapping("/getSplashAdvertise")
    @ApiOperation(value = "NO:5-1-1 随机获取一条闪屏广告 不需要登录。data 可能为null", notes = "")
    public GlobalReponse<AdvertiseVo> getSplashAdvertise() {
        List<Advertise> result = advertiseService.getList(1, 1);
        if (result.isEmpty()) {
            return GlobalReponse.success();
        }
        Advertise advertise = result.get(RandomUtils.nextInt(0, result.size()));
        return GlobalReponse.success(AdvertiseVoMapper.MAPPER.toVo(advertise));
    }

    @GetMapping("/getGrade")
    @ApiOperation(value = "NO:5-2 获取所有的年级 不需要登录", notes = "")
    public GlobalReponse<List<GradeVo>> getGrade() {
        Grade search = new Grade();
        search.setIsDeleted(false);
        List<Grade> result = gradeService.getList(search);
        return GlobalReponse.success(GradeVoMapper.MAPPER.toVo(result));
    }

    @GetMapping("/getSubject")
    @ApiOperation(value = "NO:5-2.1 获取所有的学科 不需要登录", notes = "")
    public GlobalReponse<List<SubjectVo>> getSubject() {
        Subject search = new Subject();
        search.setIsDeleted(false);
        List<Subject> result = subjectService.getList(search);
        return GlobalReponse.success(SubjectVoMapper.MAPPER.toVo(result));
    }

    @GetMapping("/getSubject/{gradeId}")
    @ApiOperation(value = "NO:5-3 获取年级下的所有学科 不需要登录", notes = "")
    public GlobalReponse<List<SubjectVo>> getSubject(@PathVariable("gradeId") Long gradeId) {
        List<Subject> result = subjectService.getListByGradeId(gradeId);
        return GlobalReponse.success(SubjectVoMapper.MAPPER.toVo(result));
    }

    @GetMapping("/getGrade/{subjectId}")
    @ApiOperation(value = "NO:5-3.1 获取学科下的所有年级 不需要登录", notes = "")
    public GlobalReponse<List<GradeVo>> getGrade(@PathVariable("subjectId") Long subjectId) {
        List<Grade> result = gradeService.getListBySubjectId(subjectId);
        return GlobalReponse.success(GradeVoMapper.MAPPER.toVo(result));
    }

    @GetMapping("/getModule/{gradeId}/{subjectId}")
    @ApiOperation(value = "NO:5-4 获取年级和学科下的模块 不需要登录", notes = "")
    public GlobalReponse<List<ModuleVo>> getModule(@PathVariable("gradeId") Long gradeId, @PathVariable("subjectId") Long subjectId) {
        Module search = new Module();
        search.setIsDeleted(false);
        search.setGradeId(gradeId);
        search.setSubjectId(subjectId);
        search.setParentId(0L);
        List<Module> result = moduleService.findByCondition(search);
        List<ModuleVo> resultVo = ModuleVoMapper.MAPPER.toVo(result);
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        resultVo.forEach(vo -> {
            if (userSubject == null) {
                vo.setAnswerCount(0L);
            } else {
                //获取用户做题数量
                ModuleRecord searchRecord = new ModuleRecord();
                searchRecord.setUserId(userSubject.getId());
                searchRecord.setParentModuleId(vo.getId());
                searchRecord.setIsDeleted(false);
                Long count = moduleRecordService.templateCount(searchRecord);
                vo.setAnswerCount(count);
            }
        });
        return GlobalReponse.success(resultVo);
    }

    @GetMapping("/getModuleDetail/{moduleId}")
    @ApiOperation(value = "NO:5-5 获取模块下的子模块 不需要登录", notes = "")
    public GlobalReponse<List<ModuleVo>> getModuleDetail(@PathVariable("moduleId") Long moduleId) {
        Module search = new Module();
        search.setIsDeleted(false);
        search.setParentId(moduleId);
        List<Module> result = moduleService.findByCondition1(search);
        List<ModuleVo> resultVo = ModuleVoMapper.MAPPER.toVo(result);
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Integer sequence=0;
        for (ModuleVo vo : resultVo) {
            if (vo.getType() == 1) {
                vo.setIsHeader(false);
                sequence+=1;
                vo.setSequence(sequence);
                if (userSubject == null) {
                    vo.setAnswerCount(0L);
                } else {
                    //获取用户做题数量
                    ModuleRecord searchRecord = new ModuleRecord();
                    searchRecord.setUserId(userSubject.getId());
                    searchRecord.setModuleId(vo.getId());
                    searchRecord.setIsDeleted(false);
                    ModuleRecord moduleRecord = moduleRecordService.templateOne(searchRecord);
                    if (moduleRecord == null) {
                        vo.setAnswerCount(0L);
                    } else {
                        vo.setAnswerCount(vo.getQuestionCount());
                    }
                }
            }else if (vo.getType()==2){
                vo.setIsHeader(true);
                sequence=0;
                List<ModuleVideo> videos = iModuleVideoDao.createLambdaQuery().andEq(ModuleVideo::getModuleId, vo.getId()).select();
                List<ModuleVideoVo> toVo = ModuleVideoVoMapper.MAPPER.toVo(videos);
                vo.setModuleVideoVos(toVo);
            }
        }
        return GlobalReponse.success(resultVo);
    }

    @GetMapping("/getModuleQuestion/{moduleId}")
    @ApiOperation(value = "NO:5-6 获取模块下的题目", notes = "")
    public GlobalReponse<List<QuestionVo>> getModuleQuestion(@PathVariable("moduleId") Long moduleId) {
        List<Question> result = questionService.findByModule(moduleId);
        Module module = moduleService.findById(moduleId);
        List<QuestionVo> vos = new ArrayList<>();
        Collections.shuffle(vos);
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        for (Question question : result) {
            QuestionVo questionVo = QuestionVoMapper.MAPPER.toVo(question);
            questionVo.set("optionList",questionVo.getOptionList());
            questionVo.setScore(module.getScore());
            if (userSubject != null) {
                questionVo.setCollect(questionService.isFavorites(userSubject.getId(), questionVo.getId()));
            }
            vos.add(questionVo);
        }
//        vos.forEach(vo -> {
//
//
//        });
        return GlobalReponse.success(vos);
    }
    @GetMapping("/getModuleVideo/{id}")
    @ApiOperation(value = "NO:5-7 获取模块视频详情", notes = "")
    public GlobalReponse<ModuleVideo> getModuleVideo(@PathVariable("id") Long id) {
        ModuleVideo video = iModuleVideoDao.single(id);
        return GlobalReponse.success(video);
    }

}
